package top.bulk.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.bulk.common.CommonResult;
import top.bulk.entity.UserEntity;
import top.bulk.entity.UserGroup;
import top.bulk.validator.group.AddGroup;
import top.bulk.validator.group.UpdateGroup;

import javax.validation.Valid;
import javax.validation.constraints.Min;

/**
 * @author 散装java
 * @version 1.0.0
 * @date 2024-06-09
 */
@RestController
@Slf4j
// 在类上，添加 @Validated 注解，表示 UserController 是所有接口都需要进行参数校验
@Validated
public class UserController {
    /**
     * 测试直接使用注解的场景 ，注意要配合 @Validated
     */
    @GetMapping("/test1")
    public CommonResult<String> test1(@RequestParam("id") @Min(value = 2L, message = "编号必须大于 2") Integer id) {
        log.info("测试再接口入参直接使用注解id:{}", id);
        return CommonResult.success("ok");
    }

    @PostMapping("/t1")
    public CommonResult<String> t1(@RequestBody UserEntity user) {
        if (user.getId() < 100) {
            throw new IllegalArgumentException("id 必须大于100");
        }
        if (user.getUsername() == null) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (user.getUsername().length() < 5 || user.getUsername().length() > 16) {
            throw new IllegalArgumentException("用户名长度在 5-16 之间");
        }
        if (!user.getUsername().matches("^[A-Za-z0-9]+$")) {
            throw new IllegalArgumentException("用户名格式为数字以及字母");
        }
        // todo 业务操作
        log.info("测试实体类接收的情况:{}", user);
        return CommonResult.success("ok");
    }

    /**
     * 测试实体类接收的情况
     * 属于嵌套场景
     */
    @PostMapping("/test2")
    public CommonResult<String> test2(@RequestBody @Valid UserEntity user) {
        log.info("测试实体类接收的情况:{}", user);
        return CommonResult.success("ok");
    }

    /**
     * 测试添加组的校验
     *
     * @param user 入参
     * @return res
     */
    @PostMapping("/testAdd")
    public CommonResult<String> testAdd(@RequestBody @Validated(AddGroup.class) UserGroup user) {
        log.info("testAdd:{}", user);
        return CommonResult.success("ok");
    }

    /**
     * 测试更新组的校验
     *
     * @param user 入参
     * @return res
     */
    @PostMapping("/testUpdate")
    public CommonResult<String> testUpdate(@RequestBody @Validated(UpdateGroup.class) UserGroup user) {
        log.info("testUpdate:{}", user);
        return CommonResult.success("ok");
    }
}
